<template>
  <header>
    <div @click="goBack">
      <i class="iconfont icon-fanhui"></i>
    </div>
    <slot>
      <form
        action=""
        onsubmit="return false"
        class="search-input"
        @keyup.enter="goSearchList"
      >
        <input v-model="inputVal" type="search" placeholder="搜索商品的名称" />
      </form>
    </slot>

    <div @click="goSearchList">
      <i class="iconfont icon-fangdajing"></i>
    </div>
  </header>
</template>

<script>
export default {
  name: 'Header',
  props: {
    queryKey: String
  },
  data () {
    return {
      inputVal: this.queryKey,
      searchArr: []
    }
  },
  methods: {
    goBack () {
      this.$router.push('/')
    },
    goSearchList () {
      // 没有搜索的值就返回
      if (!this.inputVal) return false
      // 记录
      // 如果本地存储有就追加，没有就新设置
      if (!localStorage.getItem('searchList')) {
        localStorage.setItem('searchList', '[]')
      } else {
        this.searchArr = JSON.parse(localStorage.getItem('searchList'))
      }
      // 增加数据
      this.searchArr.unshift(this.inputVal)
      // 去重后赋值
      const obj = new Set(this.searchArr)
      localStorage.setItem('searchList', JSON.stringify(Array.from(obj)))
      // 跳转

      this.$router.push({
        path: '/search-list',
        query: {
          key: this.inputVal
        }
      })
      // 清空页面
      this.inputVal = ''
    }
  }
}
</script>
<style lang="scss" scoped>
header {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 1.12rem;
  background-color: #eee;
  padding: 0 0.266667rem;
  i {
    font-size: 0.586667rem;
    color: #999;
  }
  .search-input {
    margin: 0 0.533333rem;
    input {
      width: 6.133333rem;
      height: 0.64rem;
      line-height: 0.64rem;
      padding: 0 0.693333rem 0 0.266667rem;
      border: 1px solid #ccc;
      font-size: 14px;
      color: #666;
    }
  }
}
</style>
